/**
 * 发运报表 -   
 * @author xiaoxujs
 */

import { useLocation, useNavigate } from "react-router-dom";
import { DetailsBox, EChartsBox, ShippingReportBox } from "./style";
import { Button, ConfigProvider, Input, message, Table, TableProps } from "antd";
import { useWindowFontSize } from "../../../assets/fun/Antd/configprovider";
import { useCallback, useEffect, useRef, useState } from "react";
import * as echarts from 'echarts';
import { IPlanCarShipAnalysis, IPlanCarShipDetail, IPlanCarShipDetailParams, IPlanShipTotal } from "../../../type/planManagement";
import { getPlanCarShipAnalysis, getPlanShipTotal, postPlanCarShipDetail } from "../api";
import { IFenye, INoFenye } from "../../../type/commit";
import { TablePaginationPosition } from "../../../type/antd";
import { EChartsOption } from "echarts";
import LoadingDetails from './components/LoadingDetails'

const { Search } = Input;

const ShippingReport = () => {
    const contentValue: TablePaginationPosition = "bottomCenter"; //位置
    const height = window.innerHeight;

    const location = useLocation();
    const navigate = useNavigate();

    const echartsBox = useRef<HTMLDivElement>(null);
    let echartsClass = useRef<echarts.ECharts>();
    const echartsBox1 = useRef<HTMLDivElement>(null);
    let echartsClass1 = useRef<echarts.ECharts>()

    const [jihuatongjiValue, setJihuatongjiValue] = useState<IPlanShipTotal>({
        alreadyAmount: 0,
        unshipAmount: 0,
    });
    const [searchValue, setSearchValue] = useState<string>(''); //  搜索框
    const [tableLoading, setTableLoading] = useState(false); //tableLoading
    const [listData, setListData] = useState<IPlanCarShipDetail[]>([]);
    const [paging, setPaging] = useState({
        currentPage: 1,
        pageSize: 10,
    });
    const [total, setTotal] = useState(0);
    const [loadingDetailsShow, setLoadingDetailsShow] = useState(false); // 弹窗显示
    const [clickData, setClickData] = useState<IPlanCarShipDetail>(); //  弹窗数据

    const handleEcharts = useCallback(
        async () => {
            if (echartsClass.current) {
                const { code, msg, data } = await getPlanShipTotal({ id: location.state && location.state.data.id }) as { code: number; msg: string; data: IPlanShipTotal };
                if (code === 20000) {
                    setJihuatongjiValue(data);
                    const fontSize = (size: number) => {
                        return size / 1920 * document.body.clientWidth
                    }
                    var option = {
                        // tooltip: {
                        //     trigger: 'item'
                        // },
                        // legend: {
                        //     top: '5%',
                        //     left: 'center'
                        // },
                        grid: {
                            top: '5%',    // 上内边距
                            right: '5%',  // 右内边距
                            bottom: '5%', // 下内边距
                            left: '5%'    // 左内边距
                        },
                        series: [
                            {
                                name: 'Access From',
                                type: 'pie',
                                radius: ['60%', '90%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    borderRadius: fontSize(10),
                                    // borderColor: '#fff',
                                    // borderWidth: fontSize(2)
                                },
                                label: {
                                    show: false,
                                    // position: 'center'
                                },
                                data: [
                                    { value: data.alreadyAmount, name: '已发运', itemStyle: { color: '#3370FF' } },
                                    { value: data.unshipAmount, name: '未发运', itemStyle: { color: '#DFDFDF' } },
                                ]
                            }
                        ]
                    };

                    option && echartsClass.current.setOption(option);
                    echartsClass.current.resize()
                } else {
                    message.error(msg);
                }
            }

        },
        [location.state],
    )
    const handleEchartsRight = useCallback(
        async () => {
            if (echartsClass1.current) {
                const { code, msg, data } = (await getPlanCarShipAnalysis({ planNo: location.state && location.state.data.planNo })) as INoFenye<IPlanCarShipAnalysis>;
                if (code === 20000) {
                    let arr: {
                        type: string;
                        value: number
                    }[] = [];
                    let allNum = 0;
                    data.forEach(element => {
                        arr.push({
                            type: element.carColour + element.carNo,
                            value: element.actualAmount
                        })
                        if(typeof element.actualAmount === 'number') {
                            allNum = allNum + element.actualAmount
                        }
                    });
                    if (arr.length > 0) {
                        const Xaxis = arr.map((item: any) => {
                            return item.type
                        })
                        const Yaxis = arr.map((item: any) => {
                            return item.value
                        })
                        var option: EChartsOption = {
                            // legend: {
                            //     top: '5%',
                            //     left: 'center',
                            // },
                            xAxis: {
                                type: 'category',
                                data: Xaxis,
                                nameLocation: 'end',//坐标轴名称显示位置。
                                axisLabel: {//坐标轴刻度标签的相关设置。
                                    interval: 0,
                                    rotate: 45
                                }
                            },
                            yAxis: {
                                type: 'value',
                                name: "单位：吨"
                            },
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'shadow'
                                },
                                formatter: (v: any) => {

                                    console.log("打印一下====", v);
                    
                                    const value1 = v[0].data || '0';
                    
                                    const value2 = v[0].axisValue;
                                    let value3 = 0;
                                    if(v[0].data) {
                                        value3 = (v[0].data / allNum) * 100;
                                    }
                                    
                                    return `<div>
                                    <span> ${value2}</span><br />
                    
                                    <span> ${value1 + ';' + value3.toFixed(2) + '%' }</span><br />
                    
                                </div>`;
                                }
                            },
                            grid: {
                                // top: '10%',    // 上内边距
                                right: '5%',  // 右内边距
                                // bottom: '10%', // 下内边距
                                left: '5%'    // 左内边距
                            },
                            series: [
                                {
                                    name: "发运量",
                                    data: Yaxis,
                                    color: '#2168F6',
                                    type: 'bar',
                                    // barWidth: '50px'
                                },
                            ],
                        };
                        option && echartsClass1.current!.setOption(option);
                        echartsClass1.current.resize()
                    }
                    // setEchartList(arr);

                } else {
                    message.error(msg);
                }
            }

        },
        [location.state],
    )

    const listFun = useCallback(async (params: IPlanCarShipDetailParams) => {
        setTableLoading(true);
        const { code, msg, data } = (await postPlanCarShipDetail(params)) as IFenye<IPlanCarShipDetail>;
        if (code === 20000) {
            setListData(data.records);
            setPaging({
                currentPage: params.currentPage,
                pageSize: params.pageSize,
            })
            setTotal(data.total);
            setTableLoading(false);
        } else {
            message.error(msg);
        }

    }, []);
    useEffect(() => {
        console.log('adasd')
        const params = {
            planNo: location.state && location.state.data.planNo,
            currentPage: 1,
            pageSize: 10
        }
        listFun(params);
    }, [listFun, location.state])


    useEffect(() => {
        var echarts_box_html = document.getElementById('echarts_box')!;
        echartsClass.current = echarts.init(echarts_box_html);
        handleEcharts();
    }, [handleEcharts])
    useEffect(() => {
        var echarts_box_html = document.getElementById('echarts_box1')!;
        echartsClass1.current = echarts.init(echarts_box_html);
        handleEchartsRight();
    }, [handleEchartsRight])
    useEffect(() => {
        window.addEventListener("resize", function () {
            if (echartsClass.current) {
                echartsClass.current.resize()
            }
            if (echartsClass1.current) {
                echartsClass1.current.resize()
            }
        });
        return () => { }
    }, [])

    // 获取
    const handleSearch = (value: string) => {
        const params = {
            planNo: location.state && location.state.data.planNo,
            carNo: value,
            currentPage: 1,
            pageSize: 10
        }
        listFun(params);
    }
    // 装车明细 回调
    const handleLoadingDetailsCallback = () => {
        setLoadingDetailsShow(false);
        setClickData(undefined);
    }


    const pagination = {
        //分页
        position: [contentValue],
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        // showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${total}条`,
        //每页条数
        pageSize: paging.pageSize,
        //当前页数
        current: paging.currentPage,
        //数据总数
        total: total,
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current: number, pageSize: number) => {
            const params = {
                planNo: location.state && location.state.data.planNo,
                carNo: searchValue,
                currentPage: current,
                pageSize: pageSize
            }
            listFun(params)
        },
    };

    const columns: TableProps<IPlanCarShipDetail>['columns'] = [
        {
            title: '序号',
            align: 'center',
            render: (_, record, index) => (
                <span>{(paging.currentPage - 1) * paging.pageSize + index + 1}</span>
            ),
        },
        {
            title: '车牌号',
            dataIndex: 'carNo',
            align: 'center',
        },
        {
            title: '司机姓名',
            dataIndex: 'driverName',
            align: 'center',
        },
        {
            title: '司机电话',
            dataIndex: 'driverPhoneNumber',
            align: 'center',
        },
        {
            title: '实装量(吨)',
            dataIndex: 'actualAmount',
            align: 'center',
        },
        {
            title: '总占比',
            dataIndex: 'percent',
            align: 'center',
            render: text => <span>{text && text + '%'}</span>
        },
        {
            title: '操作',
            align: "center",
            render: (_, record) => <>
                <Button type="link" onClick={() => {
                    setLoadingDetailsShow(true);
                    setClickData(record);
                }}>
                    查看明细
                </Button>
            </>
        },
    ];


    return <ShippingReportBox $height={height - 60}>
        <div className="title_box">
            <div className="goback_box" onClick={() => navigate(-1)}>
                <span className="iconfont">&#xe641;</span>
                <span>返回</span>
            </div>
            <div className="title_text">
                <span>发运报表</span>
            </div>
        </div>
        <DetailsBox>
            <div className="details_item">
                <div className="details_item_title">计划编号：</div>
                <div className="details_item_text">{location.state && location.state.data.planNo}</div>
            </div>
            <div className="details_item">
                <div className="details_item_title">计划日期：</div>
                <div className="details_item_text">{location.state && location.state.data.startDate + '~'}{location.state && location.state.data.stopDate}</div>
            </div>
            <div className="details_item">
                <div className="details_item_title">货品：精煤</div>
                <div className="details_item_text">{location.state && location.state.data.goodsName}</div>
            </div>
            <div className="details_item">
                <div className="details_item_title">物流单位：河南热力运输有限公司</div>
                <div className="details_item_text">{location.state && location.state.data.transportNames}</div>
            </div>
        </DetailsBox>
        <EChartsBox>
            <div className="echarts_left_box">
                <div className="echarts_title">发运量统计</div>
                <div className="echarts_neirong_box">
                    <div className="echarts_box_echarts_item">
                        <div id="echarts_box" style={{
                            width: '100%',
                            height: '100%',
                            // backgroundColor: '#fff',
                            // flex: '1'
                        }} ref={echartsBox}>
                        </div>
                        <div className="dingwei">
                            <div className="value">{jihuatongjiValue?.alreadyAmount + jihuatongjiValue?.unshipAmount}</div>
                            <div>计划量</div>
                        </div>
                    </div>
                    <div className="tupianjieshi_box">
                        <div className="tupianjieshi_item" style={{ color: '#3370FF', marginBottom: '4rem' }}>
                            <div className="dian" style={{ background: '#3370FF' }}></div>
                            <div className="text">已发运  {jihuatongjiValue?.alreadyAmount} 吨</div>
                        </div>
                        <div className="tupianjieshi_item">
                            <div className="dian" ></div>
                            <div className="text">未发运   {jihuatongjiValue?.unshipAmount} 吨</div>
                        </div>
                    </div>

                </div>
            </div>
            <div className="echarts_right_box">
                <div className="echarts_title">车辆发运分析</div>
                <div id="echarts_box1" style={{
                    width: '100%',
                    height: '100%',
                    // backgroundColor: '#fff',
                }} ref={echartsBox1}></div>
            </div>
        </EChartsBox>
        <div className="add_search_box">
            <div className="title">车辆发运明细</div>
            <div className="search_box">
                <Search
                    value={searchValue}
                    style={{ width: '27.3rem' }}
                    placeholder="搜索车牌号"
                    allowClear
                    onChange={(e) => {
                        setSearchValue(e.target.value)
                        if (e.target.value === '') {
                            const params = {
                                planNo: location.state && location.state.data.planNo,
                                currentPage: 1,
                                pageSize: 10
                            }
                            listFun(params);
                        }
                    }}
                    onSearch={(value) => handleSearch(value)}
                /></div>

        </div>
        <ConfigProvider theme={{
            components: {
                Table: {
                    headerColor: '#8B9BAC',
                    cellFontSize: useWindowFontSize(14),
                    cellPaddingBlock: 7
                }
            }
        }}>
            <Table<IPlanCarShipDetail>
                pagination={pagination}
                rowKey='id'
                columns={columns}
                dataSource={listData}
                loading={tableLoading}
                style={{ border: '0.1rem solid #F3F3F3' }}
            />
        </ConfigProvider>
        <LoadingDetails open = {loadingDetailsShow} clickData = {clickData} handleCallback = {handleLoadingDetailsCallback} />
    </ShippingReportBox>
}

export default ShippingReport;